package mephisto.rest.resources;

import mephisto.model.ContentDescriptor;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

import sun.reflect.ReflectionFactory.GetReflectionFactoryAction;

public class PageResource extends Resource {

    public PageResource(Context context, Request request, Response response) {
        super(context, request, response);
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
        getVariants().add(new Variant(MediaType.IMAGE_ALL));
    }

    @Override
    public Representation represent(Variant variant) {

        try {
            String key = (String) getRequest().getAttributes().get("key");
            if (key == null)
                key = "main";
            mephisto.Context context = new mephisto.Context();
            ContentDescriptor descriptor = new ContentDescriptor(key);
            context.put("cdescriptor", descriptor);
            context.put("form", getRequest().getOriginalRef().getQueryAsForm());
            //econtext.put("form",
            if (key.indexOf("css") >= 0) {
                String output = mephisto.getContentService().getContent(key, context).getContent();
                Representation representation = new StringRepresentation(output, MediaType.TEXT_HTML);
                return representation;
                   
            } else {
                String output = mephisto.getContentService().getLaidOutRenderedContent(key, context);
                Representation representation = new StringRepresentation(output, MediaType.TEXT_HTML);
                getResponse().setStatus(Status.SUCCESS_OK);
                return representation;
            }
        } catch (Exception e) {
            Representation representation = new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN);
            getResponse().setEntity(representation);
            getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
            e.printStackTrace();
            return representation;

        }

    }

    public boolean allowPut() {
        return false;
    }

    @Override
    public boolean allowDelete() {
        return false;
    }

    @Override
    public void handlePut() {
    }

    @Override
    public void handleDelete() {
    }

}
